<template>
  <el-main class="statistics-main">
    <el-card class="statistics-card">
      <template #header>
        <div class="card-header">
          <span>统计分析</span>
        </div>
      </template>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="土地用途面积占比" name="landUseArea">
          <div class="chart-container">
            <div v-if="loading" class="chart-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>数据加载中...</span>
            </div>
            <div v-else-if="error" class="chart-error">
              <el-icon><Warning /></el-icon>
              <span>{{ error }}</span>
            </div>
            <div v-else-if="!hasData" class="chart-placeholder">
              <span>暂无数据</span>
            </div>
            <div v-else ref="landUseAreaChartRef" class="chart"></div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="土地类型数量统计" name="landTypeCount">
          <div class="chart-container">
            <div v-if="loading" class="chart-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>数据加载中...</span>
            </div>
            <div v-else-if="error" class="chart-error">
              <el-icon><Warning /></el-icon>
              <span>{{ error }}</span>
            </div>
            <div v-else-if="!hasData" class="chart-placeholder">
              <span>暂无数据</span>
            </div>
            <div v-else ref="landTypeCountChartRef" class="chart"></div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="土地用途变更历史" name="landUseChange">
          <div class="chart-container">
            <div v-if="loading" class="chart-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>数据加载中...</span>
            </div>
            <div v-else-if="error" class="chart-error">
              <el-icon><Warning /></el-icon>
              <span>{{ error }}</span>
            </div>
            <div v-else-if="!hasData" class="chart-placeholder">
              <span>暂无数据</span>
            </div>
            <div v-else ref="landUseChangeChartRef" class="chart"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </el-main>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { Loading, Warning } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Query from '@arcgis/core/rest/support/Query'

// 当前激活的标签页
const activeTab = ref('landUseArea')

// 图表DOM引用
const landUseAreaChartRef = ref<HTMLElement | null>(null)
const landTypeCountChartRef = ref<HTMLElement | null>(null)
const landUseChangeChartRef = ref<HTMLElement | null>(null)

// 图表实例
let landUseAreaChart: echarts.ECharts | null = null
let landTypeCountChart: echarts.ECharts | null = null
let landUseChangeChart: echarts.ECharts | null = null

// 数据状态
const loading = ref(false)
const error = ref('')
const landUseData = ref<Array<{ name: string; value: number }>>([])
const landTypeData = ref<Array<{ name: string; count: number }>>([])
const landUseChangeData = ref<Array<{ name: string; value: number }>>([])

// 是否有数据
const hasData = computed(() => {
  if (activeTab.value === 'landUseArea') {
    return landUseData.value.length > 0
  } else if (activeTab.value === 'landTypeCount') {
    return landTypeData.value.length > 0
  } else if (activeTab.value === 'landUseChange') {
    return landUseChangeData.value.length > 0
  }
  return false
})

// 监听标签页变化，重新渲染图表
watch(activeTab, () => {
  setTimeout(() => {
    if (activeTab.value === 'landUseArea') {
      renderLandUseAreaChart()
    } else if (activeTab.value === 'landTypeCount') {
      renderLandTypeCountChart()
    } else if (activeTab.value === 'landUseChange') {
      renderLandUseChangeChart()
    }
  }, 0)
})

// 初始化
onMounted(async () => {
  await fetchData()
  renderCharts()

  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  landUseAreaChart?.resize()
  landTypeCountChart?.resize()
  landUseChangeChart?.resize()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  error.value = ''

  try {
    // 创建地块图层查询
    const landParcelLayer = new FeatureLayer({
      url: 'https://services5.arcgis.com/4AiL0yfsDkakGbRW/arcgis/rest/services/landFeaturelayer/FeatureServer/0'
    })

    // 查询所有地块
    const query = new Query()
    query.where = 'landUse IS NOT NULL and landType IS NOT NULL and OldUseType IS NOT NULL'
    query.outFields = ['*']
    query.returnGeometry = false

    const result = await landParcelLayer.queryFeatures(query)
    console.log(result.features)
    if (result.features.length === 0) {
      error.value = '未找到地块数据'
      return
    }

    // 处理土地用途面积数据
    const landUseMap = new Map<string, number>()
    // 处理土地类型数量数据
    const landTypeMap = new Map<string, number>()
    // 处理土地用途变更历史数据
    const landUseChangeMap = new Map<string, number>()

    result.features.forEach(feature => {
      const attrs = feature.attributes
      // 土地用途面积统计
      const landUse = attrs.landUse || '未分类'
      const area = attrs.Shape__Area || 0

      if (landUseMap.has(landUse)) {
        landUseMap.set(landUse, landUseMap.get(landUse)! + area)
      } else {
        landUseMap.set(landUse, area)
      }

      // 土地类型数量统计
      const landType = attrs.landType || '未分类'

      if (landTypeMap.has(landType)) {
        landTypeMap.set(landType, landTypeMap.get(landType)! + 1)
      } else {
        landTypeMap.set(landType, 1)
      }

      // 土地用途变更历史统计
      if (attrs.OldUseType) {
        try {
          // 解析OldUseType JSON字符串
          const oldUseTypes = JSON.parse(attrs.OldUseType)

          if (Array.isArray(oldUseTypes) && oldUseTypes.length > 0) {
            // 统计每种用途类型变更的次数
            oldUseTypes.forEach(oldType => {
              const changeType = `${oldType} → ${landUse}`

              if (landUseChangeMap.has(changeType)) {
                landUseChangeMap.set(changeType, landUseChangeMap.get(changeType)! + 1)
              } else {
                landUseChangeMap.set(changeType, 1)
              }
            })
          }
        } catch (e) {
          console.error('解析OldUseType失败:', e)
        }
      }
    })

    // 转换为图表数据格式
    landUseData.value = Array.from(landUseMap.entries()).map(([name, value]) => ({
      name,
      value
    }))

    landTypeData.value = Array.from(landTypeMap.entries()).map(([name, count]) => ({
      name,
      count
    }))

    landUseChangeData.value = Array.from(landUseChangeMap.entries()).map(([name, value]) => ({
      name,
      value
    }))

  } catch (err) {
    console.error('获取数据失败:', err)
    error.value = '获取数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 渲染图表
const renderCharts = () => {
  if (activeTab.value === 'landUseArea') {
    renderLandUseAreaChart()
  } else if (activeTab.value === 'landTypeCount') {
    renderLandTypeCountChart()
  } else if (activeTab.value === 'landUseChange') {
    renderLandUseChangeChart()
  }
}

// 渲染土地用途面积占比饼图
const renderLandUseAreaChart = () => {
  if (!landUseAreaChartRef.value) return

  // 初始化图表
  if (!landUseAreaChart) {
    landUseAreaChart = echarts.init(landUseAreaChartRef.value)
  }

  // 图表配置
  const option: echarts.EChartsOption = {
    title: {
      text: '不同用途土地面积占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 平方米 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: landUseData.value.map(item => item.name)
    },
    series: [
      {
        name: '土地面积',
        type: 'pie',
        radius: '50%',
        center: ['50%', '60%'],
        data: landUseData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}: {d}%'
        }
      }
    ]
  }

  // 设置图表配置
  landUseAreaChart.setOption(option)
}

// 渲染土地类型数量统计柱状图
const renderLandTypeCountChart = () => {
  if (!landTypeCountChartRef.value) return

  // 初始化图表
  if (!landTypeCountChart) {
    landTypeCountChart = echarts.init(landTypeCountChartRef.value)
  }

  // 图表配置
  const option: echarts.EChartsOption = {
    title: {
      text: '不同类型土地数量统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: landTypeData.value.map(item => item.name),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '地块数量',
        type: 'bar',
        data: landTypeData.value.map(item => item.count),
        itemStyle: {
          color: '#5470c6'
        }
      }
    ]
  }

  // 设置图表配置
  landTypeCountChart.setOption(option)
}

// 渲染土地用途变更历史图表
const renderLandUseChangeChart = () => {
  if (!landUseChangeChartRef.value) return

  // 初始化图表
  if (!landUseChangeChart) {
    landUseChangeChart = echarts.init(landUseChangeChartRef.value)
  }

  // 图表配置
  const option: echarts.EChartsOption = {
    title: {
      text: '土地用途变更历史统计',
      left: 'center',
      subtext: '显示土地用途从一种类型变更为另一种类型的次数',
      subtextStyle: {
        color: '#999',
        fontSize: 12
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 次 ({d}%)',
      backgroundColor: 'rgba(255,255,255,0.8)',
      borderColor: '#ccc',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll',
      data: landUseChangeData.value.map(item => item.name),
      formatter: function(name) {
        // 截断过长的名称
        if (name.length > 15) {
          return name.substring(0, 15) + '...';
        }
        return name;
      },
      tooltip: {
        show: true,
        formatter: function(params) {
          return params.name;
        }
      }
    },
    series: [
      {
        name: '变更次数',
        type: 'pie',
        radius: ['40%', '70%'], // 环形图
        center: ['50%', '60%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
            formatter: '{b}\n{c} 次'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: landUseChangeData.value
      }
    ]
  }

  // 设置图表配置
  landUseChangeChart.setOption(option)
}
</script>

<style lang="scss" scoped>
.statistics-main {
  padding: 0;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.statistics-card {
  width: 100%;
  height: 100%;
  margin: 0;
  border-radius: 0;
  box-shadow: none;
  display: flex;
  flex-direction: column;

  :deep(.el-card__header) {
    padding: 12px 20px;
    background-color: var(--land-background-light);
    border-bottom: 1px solid var(--land-border-color);
  }

  :deep(.el-card__body) {
    flex: 1;
    padding: 0;
    overflow: auto;
  }

  :deep(.el-tabs) {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 20px;
    background-color: var(--land-background-light);
  }

  :deep(.el-tabs__content) {
    flex: 1;
    padding: 20px;
    overflow: auto;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: var(--land-primary);
  font-size: 16px;
}

.chart-container {
  height: calc(100vh - 180px);
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid var(--land-border-color);
}

.chart-placeholder {
  color: var(--land-text-light);
  font-style: italic;
  text-align: center;
}

.chart-loading,
.chart-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--land-text-light);
  gap: 10px;
}

.chart-error {
  color: var(--el-color-danger);
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
